package com.omiis.wechat.performance_test2;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class OmiisResponseMessageHandler extends ResponseMessageHandler {
	private static Logger logger = LoggerFactory.getLogger(OmiisResponseMessageHandler.class);

	public OmiisResponseMessageHandler(VUser vUser) {
		super();
		this.setvUser(vUser);
	}

	private VUser vUser;

	private Map<String, String> agent = new ConcurrentHashMap<String, String>();

	@Override
	public void call(Object... args) {
		if (ArrayUtils.isEmpty(args)) {
			return;
		}
		JSONObject jsonObject = (JSONObject) args[0];
		BusMessage busMessage = GsonUtil.json2Object(jsonObject.toString(), BusMessage.class);
		String msgType = busMessage.getMsgType();
		logger.info("收到全媒体服务信息: {}，消息类型：{}", jsonObject, msgType);
		switch (msgType) {
		case "EVENT_REGISTER_COMPLETED":
			logger.info("注册成功。");
			Map<String, String> message = new HashMap<String, String>();
			if ("AGENT".equals(vUser.getSenderRole())) {
				message.put("channelId", getvUser().getChannelId());
				message.put("conversationId", getvUser().getConversationId());
				message.put("senderId", getvUser().getSenderId());
				message.put("senderRole", getvUser().getSenderRole());
				message.put("msgType", "SET_READY");
				getMessager().sendMessage(message);
			} else if ("CUSTOMER".equals(vUser.getSenderRole())) {
				message.put("channelId", getvUser().getChannelId());
				message.put("conversationId", getvUser().getConversationId());
				message.put("senderId", getvUser().getSenderId());
				message.put("senderRole", getvUser().getSenderRole());
				message.put("msgType", ConversationType.RESOURCE_REQUEST.toString());
				message.put("msgContent", "QUERY");
				agent.put("agentId", "");
				getMessager().sendMessage(message);
			}
			break;
		case "TEXT":
			logger.info("收到文本信息。");
			processTextMessage(busMessage);
			break;
		case "AUDIO":
			processVoiceMessage(busMessage);
			break;
		case "VIDEO":
			processVideoMessage(busMessage);
			break;
		case "IMAGE":
			processImageMessage(busMessage);
			break;
		case "EVENT_TALK":
			logger.info("接入坐席。");
			processEventTalk(busMessage);
			break;
		case "EVENT_WAITING":
			logger.info("当前坐席繁忙。");
			processEventWaiting(busMessage);
			break;
		case "EVENT_QUEUE_UPDATE":
			// TODO 排队数更新
			break;
		case "EVENT_HANGUP_ARRIVED":
			// TODO 收到客服人员发起的挂机事件
			break;
		case "EVENT_HANGUP_COMPLETED":
			// TODO 客户自己发起了挂机请求，服务器反馈挂机成功
			break;
		case "EVENT_DISCONNECT_ARRIVED":
			// TODO 客服人员掉线
			break;
		case "EVENT_TRANSFER_ARRIVED":
			// TODO 客服人员把客户的对话转接给其它客服人员
			break;
		case "EVENT_CONFERENCE_ARRIVED":
			// TODO 有第三方加入到对话中
			break;
		case "EVENT_MONITOR_ARRIVED":
			// TODO 监听事件到达（注：需要在receiverId中，增加监听者的ID。多ID之前通过逗号","分隔）
			break;
		case "EVENT_MONITOR_RELEASED":
			// TODO 释放监听（注：需要在receiverId中，移除监听者的ID。）
			break;
		case "EVENT_TAKEOVER_ARRIVED":
			// TODO 接管事件到达（注：除了在界面中知会客户外，还需要更新receiverId。）
			break;
		case "SATISFACTION_SURVEY":
			processSatisfactionSurvey(busMessage);
			break;
		}
	}

	private void processEventTalk(BusMessage bm) {
		logger.info("here,send msg to agent,bm:{}.", bm);
		agent.put("agentId", bm.getReceiverId());
		logger.info("坐席接入，busMessage：{}。", bm);
		for (int i = 0; i < getvUser().getTxtMessages().size(); i++) {
			if (i >= 10) {
				break;
			}
			String content = getvUser().getTxtMessages().get(i);
			Map<String, String> message = new HashMap<String, String>();
			message.put("channelId", bm.getChannelId());
			message.put("conversationId", bm.getConversationId());
			message.put("senderId", bm.getSenderId());
			message.put("receiverId", bm.getReceiverId());
			message.put("senderRole", bm.getSenderRole());
			message.put("msgType", "TEXT");
			message.put("msgContent", content);
			getMessager().sendMessage(message);
		}
		if ("CUSTOMER".equals(getvUser().getSenderRole())) {
			try {
				Thread.currentThread().sleep(10 * 1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			logger.info("senderId:{},all msg send done,now send hangup msg.", getvUser().getSenderId());
			Map<String, String> message = new HashMap<String, String>();
			message.put("channelId", bm.getChannelId());
			message.put("conversationId", bm.getConversationId());
			message.put("senderId", bm.getSenderId());
			message.put("receiverId", bm.getReceiverId());
			message.put("senderRole", bm.getSenderRole());
			message.put("msgType", ConversationType.HANGUP.toString());
			logger.info("发送结束对话请求，{}。", message);
			getMessager().sendMessage(message);
			try {
				Thread.currentThread().sleep(100);
			} catch (InterruptedException e) {
				logger.error(e.getMessage(), e);
			}
			getvUser().getResult().put("status", "ok");
			synchronized (getvUser().getResult()) {
				getvUser().getResult().notifyAll();
			}
		}
	}

	private void processSatisfactionSurvey(BusMessage bm) {

	}

	private void processEventWaiting(BusMessage bm) {
		if ("CUSTOMER".equals(getvUser().getSenderRole())) {
			agent.put("agentId", "");
			// synchronized (agent) {
			// try {
			// agent.wait(60 * 1000);
			// } catch (InterruptedException e) {
			// logger.error(e.getMessage(), e);
			// }
			// }
			// if (StringUtils.isEmpty(agent.get("agentId"))) {
			//
			// Map<String, String> message = new HashMap<String, String>();
			// message.put("channelId", bm.getChannelId());
			// message.put("conversationId", bm.getConversationId());
			// message.put("senderId", bm.getSenderId());
			// message.put("receiverId", bm.getReceiverId());
			// message.put("senderRole", bm.getSenderRole());
			// message.put("msgType", ConversationType.HANGUP.toString());
			// getMessager().sendMessage(message);
			// getvUser().getResult().put("status", "ok");
			// synchronized (getvUser().getResult()) {
			// getvUser().getResult().notifyAll();
			// }
			// logger.info("获取坐席超时，放弃！");
			// }
		}
	}

	private void processTextMessage(BusMessage bm) {

	}

	private void processImageMessage(BusMessage bm) {
		Map<String, String> userBaseInfo = new HashMap<String, String>();
		Map<String, String> userSessionInfo = new HashMap<String, String>();

	}

	private void processVoiceMessage(BusMessage bm) {

	}

	private void processMusicMessage(BusMessage bm) {
	}

	private void processVideoMessage(BusMessage bm) {

	}

	/**
	 * @return the vUser
	 */
	public VUser getvUser() {
		return vUser;
	}

	/**
	 * @param vUser
	 *            the vUser to set
	 */
	public void setvUser(VUser vUser) {
		this.vUser = vUser;
	}

}
